package cn.edu.tsinghua.thss.alg.closestpair.gui;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;

import cn.edu.tsinghua.thss.alg.closestpair.model.Point;

public class PointsPanel extends Canvas implements MouseListener,
		MouseMotionListener {
	private JFrame frame;

	private int x1, y1, x2, y2;

	private ArrayList<double[]> points;

	public double[][] getPoints() {
		int size = points.size();
		double[][] pts = new double[size][2];
		for (int i = 0; i < size; i++) {
			pts[i][0] = ((double[]) (points.get(i)))[0];
			pts[i][1] = ((double[]) (points.get(i)))[1];
		}
		return pts;
	}

	boolean finished = false;

	public PointsPanel(JFrame frame) {
		this.frame = frame;
		this.points = new ArrayList<double[]>();
		this.setBackground(Color.WHITE);
		this.addMouseListener(this);
		this.addMouseMotionListener(this);
	}

	public void drawLine(double x1, double y1, double x2, double y2) {
		this.x1 = (int) x1;
		this.x2 = (int) x2;
		this.y1 = (int) y1;
		this.y2 = (int) y2;
		finished = true;
		repaint();
	}

	public void paint(Graphics g) {
		super.paint(g);

		if (!finished) {
			g.setColor(Color.BLACK);
			for (double[] p : points)
				g.fillOval((int) p[0], (int) p[1], 2, 2);
		} else {
			for (double[] p : points)
				g.fillOval((int) p[0], (int) p[1], 2, 2);
			g.drawLine(x1, y1, x2, y2);
		}
	}

	public void mouseClicked(MouseEvent e) {
		double[] p = new double[2];
		p[0] = e.getX();
		p[1] = e.getY();
		points.add(p);
		repaint();
	}

	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	/**
	 * Show the point where the mouse is pressed
	 */
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	public void mouseDragged(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	/**
	 * Show the position of the mouse in the status bar when it moves around.
	 */
	public void mouseMoved(MouseEvent e) {
		((ClosestPairFrame) frame).getStatusBar().setMessage(
				"(" + e.getX() + "," + e.getY() + ")");
		frame.validate();
	}
}
